package user

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"gitee.com/bobo-rs/innovideo-services/library/tools"
	"time"
)

const (
	forgotExpire    = time.Minute * 10 // 找回密码相关校验维持效期10分钟
	updatePwdExpire = time.Minute * 10 // 修改密码-效期校验10分钟
)

// GetForgotPwdMac 获取找回密码手机号
func (u *sUser) GetForgotPwdMac(ctx context.Context) (string, error) {
	key, err := u.GetForgotPwdKey(ctx)
	if err != nil {
		return ``, exception.New(err.Error())
	}
	r, err := sredis.NewCache().Get(ctx, key)
	if err != nil {
		return ``, exception.New(`找回密码，手机号不存在`)
	}
	return r.String(), nil
}

// SetForgotPwdMac 设置用户找回密码短信手机号
func (u *sUser) SetForgotPwdMac(ctx context.Context, mobile string) error {
	key, err := u.GetForgotPwdKey(ctx)
	if err != nil {
		return err
	}
	// 设置手机号
	return sredis.NewCache().Set(ctx, key, mobile, forgotExpire)
}

// RemoveForgotPwdMac 找回密码-销毁缓存手机号-避免重复使用
func (u *sUser) RemoveForgotPwdMac(ctx context.Context) error {
	key, err := u.GetForgotPwdKey(ctx)
	if err != nil {
		return err
	}
	_, err = sredis.NewCache().Remove(ctx, key)
	return err
}

// GetForgotPwdCaptcha 找回密码-获取校验验证码
func (u *sUser) GetForgotPwdCaptcha(ctx context.Context, mobile string) (bool, error) {
	// 找回验证码KEY
	r, err := sredis.NewCache().Get(ctx, tools.CacheKey(consts.SafeForgotPwdCaptcha, mobile))
	if err != nil {
		return false, err
	}
	return r.Bool(), nil
}

// SetForgotPwdCaptcha 找回密码-设置检验验证码
func (u *sUser) SetForgotPwdCaptcha(ctx context.Context, mobile string) error {
	// 设置验证码验证
	return sredis.NewCache().Set(
		ctx, tools.CacheKey(consts.SafeForgotPwdCaptcha, mobile), true, forgotExpire,
	)
}

// RemoveForgotPwdCaptcha 找回密码-销毁验证码校验
func (u *sUser) RemoveForgotPwdCaptcha(ctx context.Context, mobile string) error {
	_, err := sredis.NewCache().Remove(
		ctx, tools.CacheKey(consts.SafeForgotPwdCaptcha, mobile),
	)
	return err
}

// GetUpdatePwdCaptcha 修改密码-获取验证码校验
func (u *sUser) GetUpdatePwdCaptcha(ctx context.Context, mobile string) (bool, error) {
	r, err := sredis.NewCache().Get(ctx, tools.CacheKey(consts.SafeUpdatePwdCaptcha, mobile))
	if err != nil {
		return false, err
	}
	return r.Bool(), nil
}

// SetUpdatePwdCaptcha 修改密码-设置验证码校验
func (u *sUser) SetUpdatePwdCaptcha(ctx context.Context, mobile string) error {
	return sredis.NewCache().Set(
		ctx, tools.CacheKey(consts.SafeUpdatePwdCaptcha, mobile), true, updatePwdExpire,
	)
}

// RemoveUpdatePwdCaptcha 修改密码-验证码已校验销毁
func (u *sUser) RemoveUpdatePwdCaptcha(ctx context.Context, mobile string) error {
	_, err := sredis.NewCache().Remove(ctx, tools.CacheKey(consts.SafeUpdatePwdCaptcha, mobile))
	return err
}

// GetForgotPwdKey 获取找回密码KEY-缓存手机号
func (u *sUser) GetForgotPwdKey(ctx context.Context) (*string, error) {
	key := tools.CacheKey(consts.SafeForgotPwdIp, utils.GetIp(ctx))
	return &key, nil
}
